<template>
  <tm-app class="work-detail-wrap">
    <tm-sheet :margin="[0, 0]" :padding="[0, 0]">
      <tm-tabs
        showTabsLineAni
        :list="DetailTabList"
        :item-width="180"
        :default-name="currentTabKey"
        active-color="#366EF4"
        :width="680"
        :showTabsLine="true"
        @change="tabChanged"
      >
      </tm-tabs>
    </tm-sheet>
    <tm-sheet :margin="[0]" v-if="isLoading">
      <tm-skeleton-line :height="50"></tm-skeleton-line>
      <tm-skeleton-line :height="50"></tm-skeleton-line>
      <view style="width: 300rpx">
        <tm-skeleton-line :height="50"></tm-skeleton-line>
      </view>
    </tm-sheet>
    <TmScrolly
      :class="viewWorkType === '待办' ? 'from-content' : 'work-detail-content'"
      v-else
    >
      <view v-if="currentTabKey === DetailType.INFO">
        <tm-sheet
          :padding="[10]"
          :margin="[0]"
          v-if="['加用户'].includes(queryData.taskType)"
        >
          <view class="mg10">{{ showContent(queryData) }}</view>
          <view class="mg10">申请时间：{{ queryData.createTime }}</view>
        </tm-sheet>
        <WorkFormView v-else />
        <!-- 审批 -->
        <tm-sheet
          :padding="[0, 20]"
          :margin="[0]"
          color="#f5f5f5"
          v-if="viewWorkType === '待办'"
        >
          <tm-form ref="form" :margin="[0]" :padding="[10]" _class="remark_mr">
            <tm-form-item>
              <tm-input
                :inputPadding="[20]"
                placeholder="请输入备注"
                :height="200"
                v-model="remark"
                confirm-hold
                showCharNumber
                :border="1"
                color="grey-5"
                type="textarea"
              ></tm-input>
            </tm-form-item>
          </tm-form>
        </tm-sheet>
        <!-- 审批信息 -->
        <tm-sheet
          :padding="[10, -20, 10, 10]"
          :margin="[0, 20]"
          v-else-if="viewWorkType !== '待办' && instanceTaskInfo"
        >
          <view class="apply-title">审批信息</view>
          <view class="mg10 flex apply-item">
            <view class="gray">审批人：</view>
            <view class="flex-sub">{{
              OrgCtrl.user.findShareById(instanceTaskInfo[0].createUser).name
            }}</view>
          </view>
          <view class="mg10 flex apply-item">
            <view class="gray">审批结果：</view>
            <view class="flex-sub">
              {{ instanceTaskInfo[0].status < 200 ? '通过' : '拒绝' }}</view
            >
          </view>
          <view class="mg10 flex apply-item">
            <view class="gray">审批时间：</view>
            <view class="flex-sub"> {{ instanceTaskInfo[0].createTime }}</view>
          </view>
          <view
            class="mg10 flex apply-item"
            v-show="instanceTaskInfo[0].comment"
          >
            <view class="gray"> 审批意见：</view>
            <view class="flex-sub">{{ instanceTaskInfo[0].comment }} </view>
          </view>
        </tm-sheet>
      </view>
      <InstanceTimeLine :instanceTaskInfo="instanceTaskInfo" v-else />
      <!-- 占位效果 -->
      <tm-sheet
        v-if="viewWorkType !== '待办'"
        :margin="[0]"
        :padding="[40]"
      ></tm-sheet>
    </TmScrolly>
    <view class="flex flex-row to-bottom" v-if="viewWorkType === '待办'">
      <view class="flex-1 mr32">
        <tm-button
          :shadow="0"
          text
          form-type="reset"
          label="驳回"
          block
          @click="approveTask(false)"
        ></tm-button>
      </view>
      <view class="flex-1">
        <tm-button
          form-type="submit"
          label="通过"
          block
          @click="approveTask(true)"
        ></tm-button>
      </view>
    </view>
  </tm-app>
</template>

<script lang="ts" setup>
import { Ref, provide, ref, computed, getCurrentInstance } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import OrgCtrl from '@/ts/controller'
import { model, schema } from '@/ts/base'
import WorkFormView from './components/workFormView/index.vue'
import InstanceTimeLine from './components/instanceTimeLine/index.vue'
import { DetailTabList, DetailType } from './config'
import { CustomFormType } from './workTypes'
import { TaskStatus } from '@/ts/core/public/enums'
import { IWorkTask } from '@/ts/core/work/task'

//流程信息
// const installInfo = ref<schema.XWorkInstance>()
//当前选中tabkey
const currentTabKey = ref<DetailType.HISTORY | DetailType.INFO>(DetailType.INFO)
//表单 主子表数据
const PrimaryForms = ref<CustomFormType[]>([])
const DetailForms = ref<CustomFormType[]>([])
const taskId = ref<string>('')
const remark = ref<string>('')
const instanceInfo = ref<schema.XWorkInstance>()
let queryData = ref<any>({})
let isLoading = ref<boolean>(true)
const instanceTaskInfo = computed(() => {
  if (
    ['加用户'].includes(queryData.value.taskType) &&
    queryData.value.records
  ) {
    return queryData.value.records
  } else if (instanceInfo.value && instanceInfo.value.tasks!.length > 0) {
    return instanceInfo.value.tasks![0].records
  }
  return undefined
})

const viewWorkType = ref<string>(uni.getStorageSync('taskType') || '待办')
onLoad(query => {
  if (query && query.item) {
    if (query.item === '加用户') {
      uni.showLoading({
        title: '加载中...'
      })
      const instance: any = getCurrentInstance()?.proxy
      const eventChannel = instance.getOpenerEventChannel()
      eventChannel.on('workDetail', function (data: any) {
        queryData.value = data
        isLoading.value = false
      })
      setTimeout(() => {
        uni.hideLoading()
      }, 500)
    } else {
      let item = JSON.parse(query.item)
      taskId.value = item.taskId
      loadInstanceInfo(item.instanceId, item.belongId)
    }
  }
})

//切换展示内容
function tabChanged(tabKey: DetailType.HISTORY | DetailType.INFO) {
  currentTabKey.value = tabKey
}

// 获取办事明细
async function loadInstanceInfo(instanceId: string, belongId: string) {
  uni.showLoading({
    title: '加载中...'
  })
  const res: schema.XWorkInstance | undefined =
    await OrgCtrl.work.loadInstanceDetail(instanceId, belongId)
  if (res && res.data) {
    instanceInfo.value = res
    makeWorkForms(JSON.parse(res.data))
  }
  setTimeout(() => {
    uni.hideLoading()
  }, 500)
}
// 整理表单数据
function makeWorkForms(workData: model.InstanceDataModel): void {
  const node = workData.node
  const fields = workData.fields
  const data = workData.data
  const formNames = [...node.primaryForms, ...node.detailForms].map(v => {
    return { id: v.id, name: v.name }
  })

  node.forms.forEach(formItem => {
    const _fdata = {
      id: formItem.id,
      name: formNames.find(fm => fm.id === formItem.id)?.name ?? '',
      fields: fields[formItem.id],
      data: data[formItem.id]
    }
    switch (formItem.typeName) {
      case '主表':
        PrimaryForms.value = [...PrimaryForms.value, _fdata]
        break
      case '子表':
        DetailForms.value = [...DetailForms.value, _fdata]
        break
      default:
        break
    }
  })
  isLoading.value = false
}

provide<Ref<CustomFormType[]>>('primaryForms', PrimaryForms)
provide<Ref<CustomFormType[]>>('detailForms', DetailForms)

//通过//拒绝
async function approveTask(isAgree: boolean) {
  const TodoTasks = await OrgCtrl.work.loadTodos(false)

  let currentTask = {} as IWorkTask | undefined

  if (taskId.value) {
    currentTask = TodoTasks.find(task => task.id === taskId.value)
  } else if (queryData.value.id) {
    currentTask = TodoTasks.find(task => task.id === queryData.value.id)
  }

  if (!currentTask) {
    return
  }

  if (isAgree === true) {
    await currentTask.approvalTask(
      TaskStatus.ApprovalStart,
      remark.value ?? '同意'
    )
  } else {
    await currentTask.approvalTask(
      TaskStatus.RefuseStart,
      remark.value ?? '拒绝'
    )
  }
  uni.$emit('changeList', {})
  uni.navigateBack().then(() => {
    uni.$tm.u.toast('操作成功')
  })
}

/** 处理字符信息展示 */
const showContent = (info: schema.XWorkTask): string => {
  const infoData = JSON.parse(info.content)
  return `${infoData[0].name}[${infoData[0].typeName}]申请加入[${infoData[1].typeName}]${infoData[1].name}`
}
</script>

<style lang="scss" scoped>
.work-detail-wrap {
  .tab-list {
    padding: 0;
  }
  .from-content {
    height: calc(100vh - 130px);
    overflow-y: scroll;
  }
  .work-detail-content {
    overflow-y: scroll;
  }
  .to-bottom {
    padding: 0px 10px;
    background-color: #fff;
    height: 80px;
    display: flex;
    align-items: center;
  }
}
.mr32 {
  margin-right: 32px;
}
.mg10 {
  margin: 10px;
}
.apply-title {
  padding: 10px 0 10px 5px;
  border-bottom: 1px dashed #ddd;
  display: flex;
  align-items: center;
  font-size: 15px;
  font-weight: bold;
  &::before {
    content: '';
    display: flex;
    width: 4px;
    height: 16px;
    background: #366ef4;
    margin-right: 8px;
  }
}
.apply-item {
  .flex-sub {
    flex: 1;
    text-align: end;
  }
  .gray {
    color: #6f7686;
  }
}
</style>
